import { addWarehouseApi, editWarehouseApi } from "@/api/managementCenter/warehosueManagement";
import FormHook from "@/hook/formHook";
import { GeneraDataType } from "@/interface";
import { message } from "ant-design-vue";
export default function OperationHook(state: GeneraDataType) {
  const { formState, formDataRef, emit, type, passData, userOpts } = state;
  const { resetFields, validateIntergeHandle, validateZhInputHandle } = FormHook({ formState });
  const onFinish = () => {
    let requestFn;
    const { cnName, address, status, cityModel, warehouseManagerId, managerPhone, stateName, cityName, zoneName } = formState;
    const params: Base.GeneraDataType = {
      cnName,
      address,
      status,
      state: cityModel[0],
      city: cityModel[1],
      zone: cityModel[2],
      warehouseManagerId,
      managerPhone,
      stateName,
      cityName,
      zoneName
    };
    if (type.value === 1) {
      requestFn = addWarehouseApi;
      Reflect.deleteProperty(params, "id");
    } else {
      requestFn = editWarehouseApi;
      params.id = passData.value.id;
    }
    requestFn(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("操作成功!");
        emit("submit");
      }
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const changeWarehouseManagerHandle = () => {
    const { phone } = userOpts.value.find((t: any) => t.id === formState.warehouseManagerId);
    formState.managerPhone = phone;
  };
  const changeCityModelHandle = (value: any, selectedOptions: Array<Base.GeneraDataType>) => {
    if (selectedOptions) {
      const state = selectedOptions[0];
      formState.stateName = state.name;
      const city = selectedOptions[1];
      formState.cityName = city.name;
      const zone = selectedOptions[2];
      formState.zoneName = zone.name;
    } else {
      formState.stateName = undefined;
      formState.cityName = undefined;
      formState.zoneName = undefined;
    }
  };
  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    validateIntergeHandle,
    validateZhInputHandle,
    changeWarehouseManagerHandle,
    changeCityModelHandle
  };
}
